package org.sdp.pearproject.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.InvocationTargetException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {Throwable.class})
    @ResponseStatus(value = HttpStatus.OK)
    public JSONObject handleException(Throwable e) throws Exception {
        if (e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() != null) {
            e =  ((InvocationTargetException)e).getTargetException();
        }
        System.err.println("exception:"+e.getMessage());
        e.printStackTrace(System.err);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", -1);
        jsonObject.put("msg", e.getMessage());
        return jsonObject;
    }

}
